package com.example.controller;

import com.example.config.httpclient.GiteeAccessClient;
import com.example.config.httpclient.GiteeUsersClient;
import com.example.pojo.entity.Result;
import com.example.pojo.model.GiteeConfig;
import com.example.pojo.model.resp.GiteeAccessTokenResp;
import com.example.pojo.model.resp.GiteeUserResp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("gitee")
public class GiteeConfigController {
   @Resource
   private GiteeConfig config;
   @Resource
   private GiteeAccessClient giteeAccessClient;
    @Resource
    private GiteeUsersClient giteeUsersClient;

    /**
     * 拼接 URL 返回给前端
     *
     * @return
     */
    @GetMapping("url")
    public Result getUrl() {
        StringBuilder sb = new StringBuilder();
        /**
         * 构建一个如下的 url
         * https://gitee.com/oauth/authorize?client_id=2ad6db7e1cef9a3c85adbdb2b9a69dab1da5757b76975a2805641488e5ce009c&redirect_uri=http://127.0.0.1:8080/test/info&response_type=code&state=HelloWorld
         * 结构:
         * Gitee认证服务器网址: https://gitee.com/oauth/authorize
         *
         * 4个参数:
         * client_id:
         * redirect_uri:
         * response_type:
         * state:
         */
        sb.append(config.getAuthUrl()).append("?")
                .append("client_id").append("=").append(config.getClientId()).append("&")
                .append("redirect_uri").append("=").append(config.getRedirectUri()).append("&")
                .append("response_type").append("=").append("code").append("&")
                .append("state").append("=").append("HelloWorld");
        String url = sb.toString();

        System.out.println("url = " + url);
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        result.setData(url);
        return result;
    }

    /**
     * 获得 Gitee授权后重定向的接口
     * 获得 code信息
     * @return
     */
    @GetMapping("code")
    public Result getCode(String code,String state) {
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        //请求 accessToken
        GiteeAccessTokenResp accessToken = giteeAccessClient.getAccessToken(code, state);
        // todo 保存至数据库
        System.out.println("accessToken = " + accessToken);

        //请求 用户信息
        GiteeUserResp userInfo = giteeUsersClient.getGrantUserInfo(accessToken.getAccess_token());
        //todo 保存用户信息至数据库

        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        result.setData(userInfo);
        return result;
    }
}